<template>
  <a-row class="content">
    <a-col flex="50px">
      <a-space>
        <a-button type="primary" status="success" :disabled="status" @click="handleReception">接收</a-button>
        <a-button type="primary" status="warning" :disabled="!status" @click="handleStop">停止</a-button>
        <a-button type="primary" status="danger" @click="handleClear">清空</a-button>
      </a-space>
    </a-col>
    <a-col flex="auto" class="content-view">
      <textarea class="textarea" v-model="codeData" style="resize:none;" readonly allow-clear/>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import {onMounted, ref, inject, watch, onBeforeUnmount} from "vue";
import {useRouter} from 'vue-router';
import {SocketData} from "@/api/websocketService";

//路由
const router = useRouter();
const channelSn = ref<any>(router.currentRoute.value.query.channelSn);
const codeData = ref<any>('正在接收中，请稍等……');
const status = ref<any>(true);

// WebSocket 数据
const {data, sendData}: SocketData = inject('webSocketData', {
  data: {value: 0},
  sendData: () => {
  }
});

// 订阅
const subscribe = () => {
  sendData({
    action: 'subscribe',
    bizSn: channelSn.value
  });
}

// 取消订阅
const onSubscribe = () => {
  sendData({
    action: 'unsubscribe',
    bizSn: channelSn.value
  });
}

//接收
const handleReception = () => {
  codeData.value = "正在接收中，请稍等……";
  status.value = !status.value;
  subscribe();
}

// 停止
const handleStop = () => {
  status.value = !status.value;
  onSubscribe();
}

// 清空
const handleClear = () => {
  codeData.value = "";
}


function splitStringIntoPairs(str:any) {
  return str.match(/.{1,2}/g).join(' ');
}

watch(data, async (newVal:any) => {
  if(newVal.key == channelSn.value){
    codeData.value = splitStringIntoPairs(newVal.value);
  }
});

onMounted(async () => {
  subscribe();
})

onBeforeUnmount(() => {
  onSubscribe();
});

</script>

<style lang="less" scoped>
.content {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  flex-direction: column;
  background: var(--color-neutral-1);

  .content-view {
    width: 100%;
    margin-bottom: 20px;
    box-sizing: border-box;
    color: var(--color-neutral-8);

    .textarea{
      width: 100%;
      height: 100%;
      outline: none;
      box-shadow: none; /* 移除可能的阴影效果 */
      border: none;
      padding: 10px;
      box-sizing: border-box;
      color: var(--color-neutral-8);
      background: var(--color-neutral-2);
    }
  }
}

</style>